<template>
  <div v-loading="loading">
    <!-- 未开通 start -->
    <div v-if="list.length === 0" class="empty-container app-main-content-box">
      <div class="img">
        <img src="@/assets/icon/i-no-auth.png" alt>
      </div>
      <div class="msg">商城还未入驻店铺，快去入驻第一家店铺吧</div>
      <el-button type="primary" size="small" round @click="addStore">入驻店铺</el-button>
    </div>
    <!-- 未开通 end -->

    <!-- 已开通 start-->
    <div v-else class="shop-container">
      <!-- left 列表 -->
      <div class="left-container">
        <div class="menu-box">
          <div class="filter">
            <!-- <div class="title">店铺列表</div> -->
            <el-input v-model="filterVal" placeholder="请输入名称搜索" size="small" />
          </div>
          <div class="content">
            <el-button type="text" size="small" round icon="el-icon-plus" class="add-btn" @click="addStore">入驻新店铺
            </el-button>
            <div
              v-for="item in list"
              :key="item.storeId"
              :class="[item.shopId === activeStore.shopId ? 'active' : '']"
              class="item"
              :title="'id:' + item.shopId"
              @click="clickMenu(item)"
            >
              {{ item.name }}
              <span v-if="item.disabled" class="app-text-color-danger">(已关停)</span>
            </div>
          </div>
        </div>
      </div>

      <!--  right 配置 -->
      <div class="right-container app-main-content-box">
        <div class="right-head flexRBC">
          <div class="flexRSC">
            <div class="shop-name">{{ activeStore.name }}</div>
            <div>
              <el-tag v-if="shopInfo.disabled" type="danger" size="small" round class="tag">已关停</el-tag>
              <el-tag v-else type="primary" size="small" round class="tag">启用中</el-tag>
              <el-tag v-if="!activeStore.disabled && shopInfo.status === 1" type="success" size="small" round class="tag">正常营业
              </el-tag>
              <el-tag v-if="!shopInfo.disabled && shopInfo.status === 0" type="info" size="small" round class="tag">已打烊</el-tag>
            </div>
          </div>
          <div>
            <el-button
              v-if="!shopInfo.disabled && shopInfo.status === 1"
              type="info"
              round
              size="small"
              @click="updateStatus({ status: 0 })"
            >打烊</el-button>
            <el-button
              v-if="!shopInfo.disabled && shopInfo.status === 0"
              type="success"
              round
              size="small"
              @click="updateStatus({ status: 1 })"
            >营业</el-button>
          </div>
        </div>
        <div>
          <form-data ref="formDataRef" />
        </div>
      </div>
    </div>
    <!-- 已开通 end-->

    <!-- 组件 -->
    <DialogAddShop ref="dialogAddShop" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import DialogAddShop from './DialogAddShop/index'
import formData from './formData'
import { getAppointmentConfig, storeList, updateStoreStatus } from '@/api/reservation'
export default {
  components: {
    DialogAddShop,
    formData
  },
  data() {
    return {
      actionUrl: imgUploadUrl,
      // 状态
      loading: false,
      dialogImageVisible: false,
      // 数据
      dialogImageUrl: '',
      filterVal: '',
      activeStore: {
        storeId: null
      },
      shopInfo: {},
      list: []
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  watch: {
    'activeStore.shopId'(val) {
      if (val) {
        this.getDetail(val)
      }
    }
  },
  created() { },
  mounted() {
    // 获取数据
    this.fetchData()
  },
  methods: {
    /**
     * 数据组
     */
    // 获取数据
    fetchData() {
      this.loading = true
      Promise.all([this.getShopList()])
        .then(() => { })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取门店列表
    getShopList(mode = null) {
      return new Promise((resolve, reject) => {
        storeList()
          .then((res) => {
            this.list = res.data
            if (res.data.length > 0) {
              if (mode === 'add') {
                this.activeStore = res.data[res.data.length - 1]
              } else if (!this.storeId) {
                this.activeStore = res.data[0]
              }
            }
          })
          .catch(() => { })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取详情
    async getDetail(shopId) {
      console.log(this.activeStore)
      this.loading = true
      const { code, data } = await getAppointmentConfig({ shopId })
      if (code === 0) {
        data.isChangeTime = data.allowModifyTime
        data.isStartLimit = data.initiateReservationRestrictions === 0
        data.isCancelLimit = data.cancelReservationRestrictions === 0
        data.cancelOrderTime = data.cancelOrderTime === 0 ? 15 : data.cancelOrderTime
        // 门店概况 二维数组 str格式:  左边:右边;左边:右边;arr格式[['', '']]
        if (
          data.description &&
          data.description.length > 0 &&
          data.description !== '{}'
        ) {
          const description = []
          const arr = data.description.split(';')
          arr.forEach((v) => {
            if (v) {
              const strArr = v.split(':')
              description.push(strArr)
            }
          })
          data.description = description
        } else {
          data.description = [['', '']]
        }

        // 门店标签 str格式:标签1,标签2 arr格式[标签1,标签2]
        if (data.shopLabel && data.shopLabel.length > 0) {
          data.shopLabel = data.shopLabel.split(',')
        } else {
          data.shopLabel = ['']
        }

        data.supplyFacility = data.supplyFacility
          ? JSON.parse(data.supplyFacility)
          : []
        data.supplyService = data.supplyService
          ? JSON.parse(data.supplyService)
          : []
        data.configForm = Object.assign(
          {},
          {
            supplyFacility: data.supplyFacility,
            supplyService: data.supplyService
          }
        )
        console.log('获取到详情', data)
        this.shopInfo = data
        this.$refs.formDataRef.setQuery(data)
        this.loading = false
        this.$bus.emit('operatingState', { operatingState: (!this.activeStore.disabled && this.shopInfo.status === 1) })
      }
    },

    /**
     * 按钮组
     */
    // 开通店铺
    addStore() {
      const selectShopIds = []
      this.list.forEach((v) => {
        selectShopIds.push(v.shopId)
      })
      this.$refs.dialogAddShop.open({ selectShopIds }).then((res) => {
        this.getShopList('add')
      })
    },

    // 选择门店
    clickMenu(item) {
      this.activeStore = item
    },

    // 关停 打烊门店
    updateStatus(params) {
      let typeText = ''
      if (Object.prototype.hasOwnProperty.call(params, 'disabled')) {
        typeText = params.disabled ? '停用' : '启用'
      }
      if (Object.prototype.hasOwnProperty.call(params, 'status')) {
        typeText = params.status ? '营业' : '打烊'
      }
      this.$confirm(
        `您确定${typeText}门店：${this.activeStore.name}?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          this.loading = true
          params.shopId = this.shopInfo.shopId
          updateStoreStatus(params)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.getDetail(this.activeStore.shopId)
            })
            .catch(() => { })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => { })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 未开通 */
.empty-container {
  padding: 50px 0;
  text-align: center;

  .img {
    margin: 0 auto;
    width: 307px;
    height: 278px;
  }

  .msg {
    height: 50px;
    line-height: 50px;
    font-size: 16px;
  }
}

/* 门店 */
.shop-container {
  display: flex;

  .left-container {
    flex: 0 0 200px;
  }

  .right-container {
    flex: 1;

    .right-head {
      margin-bottom: 20px;

      .shop-name {
        margin-right: 10px;
        font-size: 20px;
        font-weight: bold;
      }

      .tag {
        margin-right: 10px;
      }
    }

    .el-textarea,
    .el-select {
      width: 500px;
    }
  }
}

/* 门店列表 */
.menu-box {
  margin-right: 10px;
  background-color: #fff;
  border-radius: 5px;
  min-height: 500px;

  .filter {
    padding: 10px;
  }

  .content {
    font-size: 14px;

    .add-btn {
      width: 100%;
    }

    .item {
      cursor: pointer;
      padding: 10px;
      width: 100%;
    }

    .active {
      color: #fff;
      background-color: $primary;
    }
  }
}

/* 上传 */
.img-list-container {
  margin: 0;
  display: inline;
  vertical-align: top;
  cursor: pointer;

  .img-item {
    position: relative;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    height: 150px;
    width: 300px;
    margin: 0 8px 8px 0;
    display: inline-block;

    .handle-icon {
      display: none;
    }

    &:hover {
      font-size: 20px;
      color: #fff;

      .handle-icon {
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);

        .icon {
          margin: 10px;
        }
      }
    }
  }
}

.upload-container ::v-deep {
  .el-upload-dragger {
    width: 298px;
    height: 148px;
  }

  .el-upload--picture-card {
    line-height: 1;
    width: 300px;
    height: 150px;
    border: none;
  }

  .el-upload-list__item {
    width: 300px;
    height: 150px;
  }
}
</style>
